﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LitTools
{
    public class BehaviourTree
    {
        private BTNode rootNode;
        private BTNodeState state;

        public BehaviourTree(BTNode rootNode)
        {
            this.rootNode = rootNode;
        }

        public BTNodeState Update()
        {
            state = rootNode.Update();
            return state;
        }

        /// <summary>
        /// 添加节点
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="childNode"></param>
        public void AddNode(BTNode parentNode, BTNode childNode)
        {
            if (parentNode is BTNode_Deocrator decoratorNode)
            {
                decoratorNode.child = childNode;
            }
            else if (parentNode is BTNode_Composite compositeNode)
            {
                compositeNode.children ??= new List<BTNode>();
                compositeNode.children.Add(childNode);
            }
            else
            {
                Debug.LogError($"{parentNode.GetType()}不能添加子节点");
            }
        }

        /// <summary>
        /// 移除节点
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="childNode"></param>
        public void RemoveNode(BTNode parentNode, BTNode childNode)
        {
            if (parentNode is BTNode_Deocrator decoratorNode)
            {
                decoratorNode.child = null;
            }
            else if (parentNode is BTNode_Composite compositeNode)
            {
                if (compositeNode.children == null) return;
                if (compositeNode.children.Count == 0) return;
                if (!compositeNode.children.Contains(childNode)) return;
                compositeNode.children.Remove(childNode);
            }
            else
            {
                Debug.LogError($"{parentNode.GetType()}不能移除子节点");
            }
        }
    }

    public enum BTNodeState
    {
        Running,
        Failure,
        Success,
    }
}